<template>
  <div class="email-login-page">
    <div class="login-container">
      <div class="login-header">
        <h1>触图万象</h1>
        <div class="title">企业级智能协同图库</div>
      </div>

      <a-form
        :model="formState"
        :rules="rules"
        class="login-form"
        @finish="handleLogin"
        :validate-trigger="['change', 'blur']"
      >
        <!-- 邮箱输入框 -->
        <a-form-item name="email">
          <a-input
            v-model:value="formState.email"
            placeholder="请输入邮箱"
            size="large"
            allow-clear
          >
            <template #prefix>
              <MailOutlined class="site-form-item-icon" />
            </template>
          </a-input>
        </a-form-item>

        <!-- 图形验证码 -->
        <a-form-item name="captchaCode">
          <a-row :gutter="8">
            <a-col :span="14">
              <a-input
                v-model:value="formState.captchaCode"
                allow-clear
                placeholder="图形验证码，区分大小写"
                size="large"
              >
                <template #prefix>
                  <SafetyOutlined class="site-form-item-icon" />
                </template>
              </a-input>
            </a-col>
            <a-col :span="10">
              <div class="captcha-container">
                <a-button
                  v-if="!captchaUrl"
                  @click="getCaptcha"
                  :disabled="formState.email === '' || countdown > 0"
                  size="large"
                  block
                >
                  {{ countdown > 0 ? `${countdown}秒后重试` : '获取图形验证码' }}
                </a-button>
                <div v-else class="captcha-image" @click="getCaptcha">
                  <img :src="captchaUrl" alt="验证码" />
                  <div class="captcha-mask">
                    <ReloadOutlined />
                    <span>{{ countdown > 0 ? `${countdown}秒后重试` : '点击刷新' }}</span>
                  </div>
                </div>
              </div>
            </a-col>
          </a-row>
        </a-form-item>

        <!-- 邮箱验证码 -->
        <a-form-item name="verifyCode">
          <a-row :gutter="8">
            <a-col :span="14">
              <a-input
                v-model:value="formState.verifyCode"
                placeholder="请输入邮箱验证码"
                size="large"
                allow-clear
              >
                <template #prefix>
                  <KeyOutlined class="site-form-item-icon" />
                </template>
              </a-input>
            </a-col>
            <a-col :span="10">
              <a-button
                type="primary"
                :disabled="isSend || formState.captchaCode === ''"
                @click="sendVerifyCode"
                size="large"
                block
              >
                {{ buttonMsg }}
              </a-button>
            </a-col>
          </a-row>
        </a-form-item>

        <!-- 登录按钮 -->
        <a-form-item>
          <a-button
            type="primary"
            html-type="submit"
            :loading="loading"
            size="large"
            block
            class="login-button"
          >
            {{ loading ? '登录中...' : '登录' }}
          </a-button>
        </a-form-item>

        <!-- 其他登录方式 -->
        <div class="login-methods">
          <a-tooltip>
            <template #title>账号密码登录</template>
            <a-button type="text" @click="router.push('/user/login')">
              <UserOutlined /> 账号密码登录
            </a-button>
          </a-tooltip>
          <a-tooltip>
            <template #title>暂未开放</template>
            <a-button type="text" @click="router.push('/user/login/sms')">
              <MobileOutlined /> 手机号登录
            </a-button>
          </a-tooltip>
          <a-tooltip>
            <template #title>暂未开放</template>
            <a-button type="text" @click="router.push('/user/register')">
              <UserAddOutlined /> 立即注册
            </a-button>
          </a-tooltip>
        </div>
      </a-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onUnmounted } from 'vue'
import { message } from 'ant-design-vue'
import {
  getCaptchaUsingGet,
  sendCodeByEmailUsingGet,
  userLoginByEmailUsingPost
} from '@/api/userController.ts'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user.ts'
import {
  MailOutlined,
  SafetyOutlined,
  KeyOutlined,
  UserOutlined,
  MobileOutlined,
  UserAddOutlined,
  ReloadOutlined
} from '@ant-design/icons-vue'

interface LoginForm {
  email: string
  verifyCode: string
  captchaCode: string
}

const formState = reactive<LoginForm>({
  email: '',
  verifyCode: '',
  captchaCode: ''
})

const router = useRouter()
const userStore = useUserStore()
const loading = ref(false)
const isSend = ref(false)
const countDown = ref(60)
const buttonMsg = ref('发送验证码')
const countdown = ref(0)
const countdownTimer = ref<number | null>(null)

// 表单验证规则
const rules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' },
  ],
  verifyCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
  captchaCode: [{ required: true, message: '请输入图形验证码', trigger: 'blur' }]
}

// 开始倒计时
const startCountdown = () => {
  countdown.value = 60
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value)
  }
  countdownTimer.value = window.setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      if (countdownTimer.value) {
        clearInterval(countdownTimer.value)
        countdownTimer.value = null
      }
    }
  }, 1000)
}

// 获取图形验证码
const captchaUrl = ref<string>('')
const getCaptcha = async () => {
  if (countdown.value > 0) {
    message.warning(`请等待 ${countdown.value} 秒后重试`)
    return
  }

  try {
    const res = await getCaptchaUsingGet({
      userAccount: formState.email,
    })
    if (res.data.code === 0 && res.data.data) {
      captchaUrl.value = res.data.data
      startCountdown()
    } else {
      message.error(res.data.message || '获取验证码失败')
    }
  } catch (err) {
    console.error('获取验证码失败:', err)
    message.error('获取验证码失败')
  }
}

// 发送邮箱验证码
const sendVerifyCode = async () => {
  if (!formState.email) {
    message.error('请先输入邮箱')
    return
  }
  if (!formState.captchaCode) {
    message.error('请先输入图形验证码')
    return
  }

  isSend.value = true
  const timer = setInterval(() => {
    countDown.value -= 1
    buttonMsg.value = `${countDown.value}s 后重新发送`
    if (countDown.value <= 0) {
      clearInterval(timer)
      isSend.value = false
      countDown.value = 60
      buttonMsg.value = '发送验证码'
    }
  }, 1000)

  try {
    const res = await sendCodeByEmailUsingGet({
      email: formState.email,
      captchaCode: formState.captchaCode
    })

    if (res.data.code === 0) {
      message.success('验证码发送成功')
    } else {
      message.error(res.data.message || '发送验证码失败')
      isSend.value = false
      countDown.value = 60
      buttonMsg.value = '发送验证码'
    }
  } catch (err) {
    console.error('发送验证码失败:', err)
    message.error('发送验证码失败')
    isSend.value = false
    countDown.value = 60
    buttonMsg.value = '发送验证码'
  }
}

// 处理登录逻辑
const handleLogin = async () => {
  loading.value = true
  try {
    const res = await userLoginByEmailUsingPost({
      email: formState.email,
      code: formState.verifyCode,
    })

    if (res.data.code === 0 && res.data.data) {
      const token = res.data.data.token
      if (token) {
        userStore.setToken(token)
      }
      userStore.setUserInfo(res.data.data)
      message.success('登录成功')
      await router.push('/')
    } else {
      message.error(res.data.message || '登录失败')
    }
  } catch (err) {
    console.error('登录失败:', err)
    message.error('登录失败，请稍后再试')
  } finally {
    loading.value = false
  }
}

// 组件卸载时清除定时器
onUnmounted(() => {
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value)
  }
})
</script>

<style scoped lang="scss">
.email-login-page {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e8f0 100%);
}

.login-container {
  width: 100%;
  max-width: 420px;
  padding: 40px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.05);
}

.login-header {
  text-align: center;
  margin-bottom: 40px;

  h1 {
    font-size: 32px;
    color: #1890ff;
    margin-bottom: 8px;
    font-weight: 600;
  }

  .title {
    font-size: 16px;
    color: #666;
  }
}

.login-form {
  :deep(.ant-form-item) {
    margin-bottom: 24px;
  }

  :deep(.ant-input-affix-wrapper) {
    padding: 8px 11px;
  }

  :deep(.site-form-item-icon) {
    color: #bfbfbf;
  }
}

.captcha-container {
  height: 40px;
  position: relative;

  .captcha-image {
    height: 100%;
    cursor: pointer;
    position: relative;
    border-radius: 4px;
    overflow: hidden;

    img {
      height: 100%;
      width: 100%;
      object-fit: contain;
    }

    .captcha-mask {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.5);
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      color: white;
      opacity: 0;
      transition: opacity 0.3s;

      span {
        font-size: 12px;
        margin-top: 4px;
      }
    }

    &:hover .captcha-mask {
      opacity: 1;
    }
  }
}

.login-button {
  height: 40px;
  font-size: 16px;
}

.login-methods {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 24px;

  :deep(.ant-btn) {
    display: flex;
    align-items: center;
    gap: 4px;
  }
}

:deep(.ant-form-item-explain-error) {
  font-size: 13px;
}
</style>
